import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: GodK
 * Date: 2024-07-23
 * Time: 21:26
 */
public class Main {
    static class MyBlockingQueue {
        private String[] data = null;
        private int head = 0;
        private int tail = 0;
        private int size = 0;

        private Object locker = new Object();

        public MyBlockingQueue(int capacity) {
            data = new String[capacity];
        }

        public void put(String s) throws InterruptedException {
            synchronized (this){
                if (size == data.length) {
                    this.wait();
                }
                data[head] = s;
                tail++;
                if (head >= data.length) {
                    head = 0;
                }
                size++;
                this.notify();
            }
        }

        public String take() throws InterruptedException {
            String ret = "";
            synchronized (this){
                if (size == 0) {
                    this.wait();
                }
                ret = data[head];
                head++;
                if(head >= data.length){
                    head = 0;
                }
                size--;
                this.notify();
            }
            return ret;
        }
    }

    public static void main(String[] args) {
        //BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(1000);
        MyBlockingQueue queue = new MyBlockingQueue(1000);

        // 生产者线程
        Thread t1 = new Thread(() -> {
            int i = 1;
            while (true) {
                try {
                    queue.put("" + i);
                    //queue.put(Integer.valueOf("" + i));
                    System.out.println("生产元素 " + i);
                    i++;
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        // 消费者线程
        Thread t2 = new Thread(() -> {
            while (true) {
                try {
                    Integer i = Integer.parseInt(queue.take());
                    //Integer i = Integer.parseInt(String.valueOf(queue.take()));
                    System.out.println("消费元素 " + i);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        t1.start();
        t2.start();
    }
}
